package com.example.demo.service;

import com.example.demo.mapper.AdminMapper;
import com.example.demo.mapper.EmployeeMapper;
import com.example.demo.mapper.OlderMapper;
import com.example.demo.model.*;
import com.example.demo.tools.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: WJ
 * Date: 2023-02-18
 * Time: 12:03
 */
@Service
public class HomeService {

    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private OlderMapper olderMapper;
    @Autowired
    private EncryptionTool encryptionTool;      // 加密工具

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisUtil redisUtil;

    public Object login(String phone, String password) {
        LoginUser user = new LoginUser();
        user.setPhone(phone);
        user.setPassword(password);
        // 将 phone 和 password 封装成一个 Authentication 对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getPhone(),user.getPassword());
        // 认证(需要接收一个存放 phone 和 password 的 Authentication 对象)
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        // 是否认证成功
        if(Objects.isNull(authenticate)){
            // 抛出异常，认证失败
            throw new RuntimeException("登录失败!");
        }
        // 从 AuthenticationContext 中拿到用户数据
        TokenUser usr = (TokenUser) authenticate.getPrincipal();
        user = usr.getUser();
        // 生成 token 令牌
        Integer id = usr.getUser().getId();
        Map<String,Object> map = new HashMap<>();
        map.put(Constant.TOKEN_KEY,id);
        String token = JWTUtils.createToken(map);
        // 把 token 封装成 key : value 的形式
        map = new HashMap<>();
        map.put("token",token);

        // 更新上一次登录的时间
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String currentDate = format.format(new Date());
        String oldDate = format.format(usr.getUser().getLogin_time());
        Integer n = adminMapper.updateTimeById(user.getId(), currentDate, oldDate);
        if(n != 1){
            return "更新时间失败!";
        }

        if(usr.getUser().getStatus().equals("超级管理员")){
            Admin admin = adminMapper.getDetailAdminInfoById(user.getId());
            admin.setPassword("");
            map.put("user",admin);
        }else if(usr.getUser().getStatus().equals("员工")){
            Employee employee = employeeMapper.getDetailInfoByEmployeeId(user.getId());
            employee.setPassword("");
            map.put("user",employee);
        }else{
            Older older = olderMapper.getOlderAllInfo(user.getId());
            older.setPassword("");
            map.put("user",older);
        }

        // 通过 redis 缓存用户数据(默认时间为 12 个小时)
        redisUtil.setCacheObject(Constant.USER_LOGIN+usr.getUser().getId(),usr,Constant.TIME_USER, TimeUnit.SECONDS);
        return map;
    }

//    获取柱状图的数据
    public Object getOption() {

        Integer[] arr = new Integer[3];

        List<LoginUser> adminTotal = adminMapper.getAdminTotal();
        List<LoginUser> employeeList = employeeMapper.getEmployeeList(null);
        List<LoginUser> olderList = olderMapper.getOlderList(null);

        if(adminTotal != null && employeeList != null && olderList != null){

            arr[0] = adminTotal.size();
            arr[1] = employeeList.size();
            arr[2] = olderList.size();

            return arr;
        }
        return "柱状图数据获取失败!";
    }

//    公告数据获取
    public Object getNoticeList(Boolean isNotice) {
        List<Notice> allNotice = adminMapper.getAllNotice();
        if(allNotice != null && allNotice.size() != 0){
//            检查需不需要截取
            if(isNotice){
                Constant.interceptBefore21(allNotice);
            }
            return allNotice;
        }else{
            return "公告数据获取失败!";
        }
    }
}
